#include "chat_message.h"
#include "client.h"
#include <boost/asio.hpp>
#include <deque>
#include <iostream>
#include <thread>

#include <cstdlib>


int main(int argc, char* argv[]) {
    try {
        if(argc != 3) {
            std::cerr << "Usage: main_client <host> <port>" << std::endl;
            return 1;
        }

        boost::asio::io_service io_service;
        tcp::resolver resolver(io_service);
        auto endpoint_iterator = resolver.resolve({argv[1], argv[2]});
        chat_client c(io_service, endpoint_iterator);

        std::thread t([&io_service]() {io_service.run(); });
        char line[chat_message::max_body_length + 1];

        // Ctrl + D 正常退出一个应用程序
        while(std::cin.getline(line, chat_message::max_body_length+1)) {
            chat_message msg;
            msg.body_length(std::strlen(line)); 
            std::memcpy(msg.body(), line, msg.body_length());
            msg.encode_header();
            c.write(msg);
        }

        c.close();
        t.join();

    }catch(std::exception& ex) {
        std::cerr << "Exception: " << ex.what() << std::endl;
    }

    return 0;
}